package top.tupobi.android_framework

import android.content.Context
import androidx.core.content.PermissionChecker
import androidx.fragment.app.FragmentActivity

object TPermission {
    private const val TAG = "INVISIBLE_PERMISSION_FRAGMENT"

    fun requestPermissions(
        activity: FragmentActivity,
        vararg permission: String,
        callback: PermissionCallback
    ) {
        val fragmentManager = activity.supportFragmentManager
        val existedFragment = fragmentManager.findFragmentByTag(TAG)
        val fragment = if (existedFragment != null) {
            existedFragment as InvisiblePermissionFragment
        } else {
            val invisiblePermissionFragment = InvisiblePermissionFragment()
            fragmentManager.beginTransaction().add(invisiblePermissionFragment, TAG).commitNow()
            invisiblePermissionFragment
        }
        fragment.requestNow(callback, *permission)
    }

    fun checkSinglePermission(context: Context, permission: String): Boolean {
        return PermissionChecker.checkSelfPermission(
            context,
            permission
        ) == PermissionChecker.PERMISSION_GRANTED
    }
}